﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FastReport;
using FastReport.Export.Pdf;
using MiniExcelLibs;
using ProductionLine.Modules.ShareLib.Helpers;
using ProductionLine.Modules.ShareLib.Models;


namespace ProductionLine.Modules.DataQuery.ViewModels;

public partial class DataQueryViewModel : ObservableObject {
    private readonly UserSession _userSession;
    /// <summary>
    /// 数据列表
    /// </summary>
    [ObservableProperty]
    List<ScadaReadData> _scadaReadDataList = new();
    /// <summary>
    /// 开始时间
    /// </summary>
    [ObservableProperty]
    DateTime _startTime = DateTime.Now.AddDays(-30);
    /// <summary>
    /// 结束时间
    /// </summary>
    [ObservableProperty]
    DateTime _endTime = DateTime.Now;
    /// <summary>
    /// 每一页多少条数据
    /// </summary>
    #region 分页实现
    [ObservableProperty]
    int _pageSize = 20;
    /// <summary>
    /// 当前为多少页
    /// </summary>
    [ObservableProperty]
    int _currentPage = 1;

    partial void OnCurrentPageChanged(int value) {
        Search();
    }
    /// <summary>
    /// 总页数
    /// </summary>
    [ObservableProperty]
    int _totalPages = 1;
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="userSession"></param>
    public DataQueryViewModel(UserSession userSession) {
        _userSession = userSession;
    }
    /// <summary>
    /// 回到第一页
    /// </summary>
    [RelayCommand]
    void GoToFirstPage() {
        CurrentPage = 1;
    }
    /// <summary>
    /// 下一页
    /// </summary>
    [RelayCommand]
    void GoToNextPage() {
        if (CurrentPage < TotalPages) {
            CurrentPage++;
        }
    }
    /// <summary>
    /// 上一页
    /// </summary>
    [RelayCommand]
    void GoToPreviousPage() {
        if (CurrentPage > 1) {
            CurrentPage--;
        }
    }
    /// <summary>
    /// 最后一页
    /// </summary>
    [RelayCommand]
    void GoToLastPage() {
        CurrentPage = TotalPages;
    }

    #endregion

    [RelayCommand]
    void Load() {
        int totalNumber = 1;
        ScadaReadDataList = SqlSugarHelper.Db.Queryable<ScadaReadData>()
            .ToPageList(CurrentPage, PageSize, ref totalNumber);//当前页，每页条数，总条数
        TotalPages = (int)Math.Ceiling((double)totalNumber / PageSize);//总页数
    }
    /// <summary>
    /// 导出分页
    /// </summary>
    [RelayCommand]
    void OutPage() {
        SaveByMiniExcel(ScadaReadDataList);
    }
    /// <summary>
    /// 导出所有
    /// </summary>
    [RelayCommand]
    void OutAll() {
        var list = SqlSugarHelper.Db.Queryable<ScadaReadData>().ToList();
        SaveByMiniExcel(list);
    }

    #region FastReport
    //Json转CVS:https://www.bejson.com/json/json2excel/
    /// <summary>
    /// 设计报表
    /// </summary>
    [RelayCommand]
    void DesignReport() {
        try {

            var report = new Report();
            // 加载报表设计文件
            var path = $@"{Environment.CurrentDirectory}\Configs\report.frx";
            report.Load(path);
            report.Design();

            // 导出 PDF
            var pdfExport = new PDFExport();
            pdfExport.Export(report);

            report.Dispose();
        } catch (Exception e) {
            MessageBox.Show(e.Message);
        }
    }

    /// <summary>
    /// 报表预览
    /// </summary>
    [RelayCommand]
    void PreviewReport() {
        try {
            var dateSet = ScadaReadDataList.ConvertToDataSet();
            var report = new Report();
            var path = $@"{Environment.CurrentDirectory}\Configs\report.frx";
            report.Load(path);
            report.RegisterData(dateSet);
            report.Prepare();
            report.ShowPrepared();
            report.Dispose();
        } catch (Exception e) {
            MessageBox.Show(e.Message);
        }
    }
    /// <summary>
    /// 报表导出
    /// </summary>
    [RelayCommand]
    void OutputReport() {
        try {
            var dateSet = ScadaReadDataList.ConvertToDataSet();
            var report = new Report();
            var path = $@"{Environment.CurrentDirectory}\Configs\report.frx";
            report.Load(path);
            report.RegisterData(dateSet);
            report.Prepare();
            // 导出 PDF
            var pdfExport = new PDFExport();
            pdfExport.Export(report);
            report.Dispose();
        } catch (Exception e) {
            MessageBox.Show(e.Message);
        }
    }
    #endregion
    /// <summary>
    /// 重置
    /// </summary>
    [RelayCommand]
    void Reset() {
        StartTime = DateTime.Now.AddDays(-30);
        EndTime = DateTime.Now;
    }
    /// <summary>
    /// 查询数据
    /// </summary>
    [RelayCommand]
    void Search() {
        if (StartTime > EndTime) {

            MessageBox.Show("开始时间不能超过结束时间");

            return;
        }

        int totalNumber = 1;//总条数
        ScadaReadDataList = SqlSugarHelper.Db.Queryable<ScadaReadData>()
            .Where(x=>StartTime<=x.CreateTime&&x.CreateTime<=EndTime)
            .ToPageList(CurrentPage, PageSize, ref totalNumber);
        TotalPages = (int)Math.Ceiling((double)totalNumber / PageSize);//总页数
    }

    /// <summary>
    /// 导出excel
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    private void SaveByMiniExcel<T>(List<T> list) {
        if (list.Count < 1) {
            return;
        }

        var rootPath = AppDomain.CurrentDomain.BaseDirectory + "\\Excels\\";

        if (!Directory.Exists(rootPath)) {
            Directory.CreateDirectory(rootPath);
        }

        var excelPath = rootPath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

        try {
            MiniExcel.SaveAs(excelPath, list);
            MessageBox.Show($"导出成功--{excelPath}");
        } catch (Exception e) {
            MessageBox.Show($"导出异常--{e.Message}");
        }
    }
}